package com.pcj.blog.Aspect;/**
 * @param
 * @author pcj
 * @date 2021/12/23 16:45
 * @return
 */

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @className LogAespect
 * @author pengcj
 * @date 2021/12/23 16:45
 */
@Aspect //切面
@Component
public class LogAspect {

    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(* com.pcj.blog.web.*.*(..) )") //切点  后面是使用的范围
    public void log(){ }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes  attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String url=request.getRequestURL().toString();
        String ip=request.getRemoteAddr();
        String classMethod=joinPoint.getSignature().getDeclaringTypeName()+","+joinPoint.getSignature().getName();
        Object [] args =joinPoint.getArgs();
        RequestLog log=new
                RequestLog(url,ip,classMethod,args);

        logger.info("Request : {}",log);
    }
    @After("log()")
    public void doAfter(){
//        logger.info("*****doAfter****");
    }

    @AfterReturning(returning = "o",pointcut = "log()")  //捕捉方法返回的内容
    public void doAfterReturn(Object o){
        logger.info("result : {}",o);
    }

    //内部类
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object [] args;

        public RequestLog(String url, String ip, String classMethod, Object [] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + args +
                    '}';
        }
    }
}
